<?php
/**
 * Created by PhpStorm.
 * User: 17628
 * Date: 2021-11-18
 * Time: 13:45
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\Address as AddressModel;
use app\admin\validate\Address as AddressValidate;

class Address extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    //地址显示
    public function index()
    {
        $model = new AddressModel();
        $list = $model
            ->field('id,name,phone,provinces,detailed,postcode')
            ->select();
        return sucessMsg('200', '获取成功', $list);
    }

    //地址添加
    public function add()
    {
        if (request()->isPost()){
            $params = $this->request->param();
            $addr = new AddressModel();
            $validate = new AddressValidate();
            if (!$validate->scene('add')->check($params)) {
                $this->error($validate->getError());
            }
            if (!preg_match('^1(3|4|5|7|8)[0-9]\d{8}$^', $params['phone'])) {
                return errMsg('手机号格式不正确');
            }
            if ($addr->save($params)) {
                return sucessMsg(200, '添加成功');
            }
            return errMsg(400, '添加失败');
        }
        return errMsg('请添加物流信息');
    }

    //地址修改
    public function update()
    {
        $postData = $this->request->post();
        $model = new AddressModel();
        $validate = new AddressValidate();
        if (!$validate->scene('edit')->check($postData)) {
            $this->error($validate->getError());
        }
        $address = $model->where(['personal_id' => $this->auth->id, 'is_default' => 1, 'status' => 1])->find();
        $model->personal_id = $this->auth->id;
        if (isset($postData['is_default']) && $postData['is_default'] == 1 && !empty($address)) {
            $address['is_default'] = -1;
            $address->save();
        }
        if (AddressModel::update($postData)) {
            $this->success('200', '用户收货地址修改成功', $postData);
        } else {
            $this->error('修改失败');
        }
    }

    //(地址管理、地址簿 )删除地址信息
    public function delete()
    {
        $model = new AddressModel();
        $id = input('id/d', 0);
        $data = $model->where('id', $id)->find();
        if (empty($data))
            return errMsg(422, '无数据！');
        if ($data->save(['id' => $id, 'status' => -1]))
            return sucessMsg(200, '删除成功');
        return errMsg(422, '删除失败');
    }

    //硬删除
    public function del()
    {
        $model = new AddressModel();
        $id = input();
        $list = $model->where('id',$id['id'])->delete();
        if($list){
            return sucessMsg('200','删除成功');
        }else{
            return errMsg('400','删除失败');
        }
    }
}